package com.ruoyi.common.core.redis;


import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

/**
 * MyMapCache
 * 替代 RedisCache
 *
 **/
@SuppressWarnings(value = { "unchecked", "rawtypes" })
@Component
public class MyCache
{
    public ConcurrentHashMap<String, Object> concurrentHashMap = new ConcurrentHashMap<>();

    private Map<String, Long> timeMap = new ConcurrentHashMap<>();


    /**
     * 缓存基本的对象，Integer、String、实体类等
     *
     * @param key 缓存的键值
     * @param value 缓存的值
     */
    public <T> void setCacheObject(final String key, final T value)
    {
        if(StringUtils.isNotEmpty(key) && ObjectUtils.isNotEmpty(value))
            concurrentHashMap.put(key, value);
    }


    /**
     * 取值
     *
     * @param key key
     * @return Object
     */
    public Object get(String key) {
        return concurrentHashMap.get(key);
    }

    /**
     * 缓存基本的对象，Integer、String、实体类等
     *
     * @param key 缓存的键值
     * @param value 缓存的值
     * @param timeout 时间
     * @param timeUnit 时间颗粒度
     */
    public <T> void setCacheObject(final String key, final T value, final Integer timeout, final TimeUnit timeUnit)
    {

        this.setCacheObject(key, value);

        if (StringUtils.isNotEmpty(key) && ObjectUtils.isNotEmpty(value) && ObjectUtils.isNotEmpty(timeout)) {
            long time = timeout*60*1000;
            long currentTime = new Date().getTime();
            timeMap.put(key,time+currentTime);
            new CleanerThread().start();
        }


    }

    public List<String> keys(String key){
        List<String> result = new ArrayList<>();
        concurrentHashMap.forEach((k,v)->{
            if(k.startsWith(key)){
                result.add(k);
            }
        });
        return result;
    }
    /**
     * 判断 key是否存在
     *
     * @param key 键
     * @return true 存在 false不存在
     */
    public Boolean hasKey(String key)
    {
        return concurrentHashMap.containsKey(key);
    }

    /**
     * 获得缓存的基本对象。
     *
     * @param key 缓存键值
     * @return 缓存键值对应的数据
     */
    public Object getCacheObject(final String key)
    {
        return  concurrentHashMap.get(key);
    }

    /**
     * 删除单个对象
     *
     * @param key key
     */
    public boolean deleteObject(final String key)
    {
        if(!hasKey(key)){
            return true;
        }
        concurrentHashMap.remove(key);
        return true;
    }

    /**
     * 删除集合对象
     *
     * @param collection 多个对象
     * @return boolean
     */
    public boolean deleteObject(final List<String> collection)
    {
        try {
            collection.forEach(this::deleteObject);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }


    class CleanerThread extends Thread {
        @Override
        public void run() {
            while (true) {
                cleanMap();
                try {
                    long expiryInMillis = 1000 * 60;
                    Thread.sleep(expiryInMillis / 2);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

        private void cleanMap() {
            long currentTime = new Date().getTime();
            for (String key : timeMap.keySet()) {
                if (currentTime > timeMap.get(key)) {
                    concurrentHashMap.remove(key);
                    timeMap.remove(key);
                }
            }
        }
    }

}
